cmake_minimum_required(VERSION 3.12)

project(csapp)

file(GLOB_RECURSE ALL_SOURCE "*.cpp" "*.c")

MESSAGE(STATUS ${ALL_SOURCE})

function(include_sub_directories_recursively root_dir)
    if (IS_DIRECTORY ${root_dir})
        message(STATUS "include dir: " ${root_dir})
        target_include_directories(${PROJECT_NAME} INTERFACE ${root_dir})
    endif()
    file(GLOB ALL_SUB RELATIVE ${root_dir} ${root_dir}/*)
    foreach(sub ${ALL_SUB})
        if (IS_DIRECTORY ${root_dir}/${sub})
            include_sub_directories_recursively(${root_dir}/${sub})
        endif()
    endforeach()
endfunction()

add_library(${PROJECT_NAME} SHARED ${ALL_SOURCE})

include_sub_directories_recursively(${CMAKE_CURRENT_SOURCE_DIR})

if(WIN32)
    # macro see @ https://stackoverflow.com/a/40217291/1746503
    macro(get_WIN32_WINNT version)
        if (CMAKE_SYSTEM_VERSION)
            set(ver ${CMAKE_SYSTEM_VERSION})
            string(REGEX MATCH "^([0-9]+).([0-9])" ver ${ver})
            string(REGEX MATCH "^([0-9]+)" verMajor ${ver})
            # Check for Windows 10, b/c we'll need to convert to hex 'A'.
            if ("${verMajor}" MATCHES "10")
                set(verMajor "A")
                string(REGEX REPLACE "^([0-9]+)" ${verMajor} ver ${ver})
            endif ("${verMajor}" MATCHES "10")
            # Remove all remaining '.' characters.
            string(REPLACE "." "" ver ${ver})
            # Prepend each digit with a zero.
            string(REGEX REPLACE "([0-9A-Z])" "0\\1" ver ${ver})
            set(${version} "0x${ver}")
        endif(CMAKE_SYSTEM_VERSION)
    endmacro(get_WIN32_WINNT)

    if(NOT DEFINED _WIN32_WINNT)
        get_WIN32_WINNT(ver)
        set(_WIN32_WINNT ${ver})
    endif()

    message(STATUS "Set _WIN32_WINNET=${_WIN32_WINNT}")

    target_compile_definitions(${PROJECT_NAME}
            INTERFACE
            _WIN32_WINNT=${_WIN32_WINNT}
            WIN32_LEAN_AND_MEAN
            )
elseif(UNIX)
    target_link_libraries(${PROJECT_NAME}
            INTERFACE pthread
            )
endif()